package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 根据用户id查询对应的资源数据
     *
     * @return
     */
    @Override
    public List<MenuVo> getMyMenus() {
        Long userId = ThreadLocalUtil.get();
        //查询数据
        List<MenuVo> menuVoList = resourceMapper.selectMenuByUserId(userId);
        //构建 parentNo -> List<MenuVo> 的映射
        Map<String, List<MenuVo>> parentMap = menuVoList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));

        //递归构建我的菜单信息
        buildTree(menuVoList, parentMap);
        return parentMap.get(SuperConstant.ROOT_RESOURCE_PARENT_ID);
    }

    /**
     * 构建菜单树形结构
     */
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "zzyl:resource:tree:vo", key = "#dto")
    @Override
    public TreeVo resourceTree(ResourceDto dto) {
        /*String redisKey = "zzyl:resource:tree:vo";
        String redisData = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotBlank(redisData)){
            return JSON.parseObject(redisData, TreeVo.class);
        }*/

        dto.setResourceType("m");
        dto.setDataState("0");
        //构建TreeItemVo对象（树形结构）
        //1.获取所有的资源对象
        List<Resource> resources = resourceMapper.selectList(dto);
        //2.获取根节点
        Resource resourceRoot = CollUtil.findOneByField(resources, "resourceNo", SuperConstant.ROOT_RESOURCE_PARENT_ID);
        //3.构建树形结构
        TreeItemVo treeItemVo = buildTreeItemVo(resourceRoot, resources);

        //创建Vo返回
        TreeVo treeVo = TreeVo.builder()
                .items(List.of(treeItemVo))
                .build();

       /* stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(treeVo));*/
        return treeVo;
    }

    /**
     * 资源列表
     */
    @Override
    public List<ResourceVo> resourceList(ResourceDto dto) {
        List<Resource> resources = resourceMapper.selectList(dto);
        //转换为Vo,拷贝，copyToList:将List<Resource>转换为List<ResourceVo>
        List<ResourceVo> resourceVos = BeanUtil.copyToList(resources, ResourceVo.class);
        return resourceVos;
    }

    /**
     * 添加资源
     *
     * @param dto
     */
    @Override
    public void addResource(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);

        String resourceNo = createResourceNo(resource, resourceMapper.selectByResourceNo(dto.getParentResourceNo()));
        resource.setResourceNo(resourceNo);
        resourceMapper.insert(resource);
    }

    /**
     * 修改资源
     *
     * @param dto
     */
    @Override
    public void updateResource(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        //判断是否有子菜单，如果有子菜单，则禁止修改
        if (resourceMapper.hasChildByMenuId(resource.getResourceNo()) > 0) {
            throw new RuntimeException("存在子菜单，不能修改");
        }
        int result = resourceMapper.updateByPrimaryKeySelective(resource);
        if (result == 0) {
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
    }

    /**
     * 启用禁用
     *
     * @param dto
     */
    @Override
    public void enable(ResourceDto dto) {
        //启用菜单
        if (StrUtil.equals(dto.getDataState(), "0")) { //0:启用，1:禁用
            //判断父级菜单是否是禁用，如果是禁用，不允许启用
            String parentResourceNo = dto.getParentResourceNo();
            Resource parentResource = resourceMapper.selectByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")) {//0:启用，1:禁用
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }

        //判断是否有子菜单，如果有子菜单，则一起启用或禁用        NoProcessing.processString(resourceNo);     101202000000 -> 101202
        String resourceNo = dto.getResourceNo();
        resourceMapper.updateByResourceNo(resourceNo, dto.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), dto.getDataState());
    }


    /**
     * 删除菜单
     *
     * @param menuId
     */
    @Override
    public void remove(Long menuId) {
        //判断是否有子菜单
        String resourceNo = String.valueOf(menuId);
        if (resourceMapper.hasChildByMenuId(resourceNo) > 0) {
            throw new RuntimeException("存在子菜单，不能删除");
        }
        resourceMapper.deleteByResourceNo(resourceNo);
    }


    /**
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     */
    private String createResourceNo(Resource resource, Resource parentResource) {
        //判断是否是按钮，如果是按钮，则不限制层级
        if (!StrUtil.equals(resource.getResourceType(), SuperConstant.BUTTON)) {
            if (NoProcessing.processString(parentResource.getResourceNo()).length() / 3 >= 5) {
                //判断资源编号是否大于三级
                //100 001 000 000 000
                //100 001 001 000 000
                //100 001 001 001 000
                //100 001 001 001 001 001
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResource.getResourceNo()).build();
        List<Resource> resources = resourceMapper.selectList(dto);
        if (ObjectUtil.isEmpty(resources)) {
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResource.getResourceNo(), false);
        } else {
            //有下属节点，在已有的节点上追加，先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }

    /**
     * 根据根节点，节点列表构建资源树形结构
     */
    private TreeItemVo buildTreeItemVo(Resource resourceRoot, List<Resource> resources) {

        //1.创建树节点
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(resourceRoot.getResourceNo())
                .label(resourceRoot.getResourceName())
                .build();

        //2.找到当前节点的子节点
        Collection<Resource> children = CollUtil.filterNew(resources, resource -> StrUtil.equals(resource.getParentResourceNo(), resourceRoot.getResourceNo()));

        //如果没有子节点，直接返回,递归结束,结束递归
        if (CollUtil.isEmpty(children)) {
            return treeItemVo;
        }

        //3.递归调用
        List<TreeItemVo> treeItemVos = children.stream().map(resource -> buildTreeItemVo(resource, resources)).collect(Collectors.toList());

        treeItemVo.setChildren(treeItemVos);

        return treeItemVo;

    }

    /**
     * 递归构建我的菜单信息（已提供）
     */
    private void buildTree(List<MenuVo> menuVoList, Map<String, List<MenuVo>> parentMap) {
        menuVoList.forEach(menuVo -> {
            //补全数据
            menuVo.setMeta(MenuMetaVo.builder().title(menuVo.getName()).build());
            menuVo.setRedirect("/" + menuVo.getName());
            //根据当前资源编号查询子资源
            List<MenuVo> childrenList = parentMap.get(menuVo.getResourceNo());
            if (CollUtil.isNotEmpty(childrenList)) {
                buildTree(childrenList, parentMap);
                menuVo.setChildren(childrenList);
            }
        });
    }
}
